package com.example.poemtest.utils;

import android.net.wifi.aware.DiscoverySession;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.example.poemtest.entity.PropInfoBean;
import com.example.poemtest.mine.MyPropActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * created by JHT on 2024/5/17
 */
public class HttpUtil {

    private static volatile OkHttpClient okHttpClient;
    private static volatile Request request;
    public static OkHttpClient okhttp() {
        okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .addNetworkInterceptor(new TokenHeaderInterceptor())
                .build();
        return okHttpClient;
    }

    /**
     * @param baseUrl   //请求的URL
     * @param formBody  //请求参数，这里是post form表单请求
     * @return
     */
    public static Request request (String baseUrl, FormBody formBody ){
        //请求的url
        request = new Request.Builder()
                .url(baseUrl)//请求的url
                .post(formBody)
                .build();
        return request;
    }

    /**
     * 拦截器
     */
    public static class TokenHeaderInterceptor implements Interceptor {
        @Override
        public Response intercept(Interceptor.Chain chain) throws IOException {
            // get token
//            String token = AppService.getToken();
            Request originalRequest = chain.request();
            // get new request, add request header
            Request updateRequest = originalRequest.newBuilder()
                    //请求头
//                    .header("token", token)
                    .build();
            return chain.proceed(updateRequest);
        }
    }

    private int code;   //返回的状态码
    private String msgCon;  //返回的错误信息
    private Handler myHandler = new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            //处理子线程发送的消息
            String result = (String) msg.obj;
            try {
                JSONObject jsonObject = new JSONObject(result);
                code = jsonObject.getInt("code");
                msgCon = jsonObject.getString("msg");
                Log.e("状态码",code+"");
                Log.e("返回的提示信息：",msgCon);
                if (code == 200){
                    //解析json文件流
                    PropInfoBean propInfoBean = com.alibaba.fastjson.JSONObject.parseObject(result,PropInfoBean.class);
                    List<PropInfoBean.PropInfo> list = propInfoBean.getData();
                    for (PropInfoBean.PropInfo propInfo : list) {
                        Constant.propInfoList.add(propInfo);
                    }
                    for (PropInfoBean.PropInfo propInfo : Constant.propInfoList) {
                        Log.e("收到的道具数据",propInfo.toString());
                    }
                } else {
//                    Toast.makeText(MyPropActivity.this,msgCon,Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };
    public void getConnMyProp() {
        //创建okhtto请求的对象
        OkHttpClient okHttpClient = new OkHttpClient();
        //创建请求连接，url里面存放请求连接，get表示其实get请求
//        Request request = new Request.Builder()
//                .url("http://192.168.43.131:8080/userInfo/login")
//                .post(requestBody)
//                .build();
        Request request = new Request.Builder()
                .url("http://192.168.43.131:8080/propInfo/findPropByUserId?userId=" + Constant.userId)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("okhttp","请求失败");
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //处理后端传递的数据
                Log.e("okhttp","请求成功");
                String responseDate = response.body().string();
                Log.e("返回的数据",responseDate);
                //数据源发送改变，需要更新界面，使用Handler
                Message message = new Message();
                message.obj = responseDate;
                myHandler.sendMessage(message);//发送到主线程的消息队列
            }
        });
    }
}
